package com.lsz.crm.aspect;


import com.lsz.crm.annotation.RequiredPermission;
import com.lsz.crm.exceptions.AuthException;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * 切面，做请求拦截权限处理
 * @Author liushizhong
 * @Date 2021/11/3 14:49
 * @Version 1.0
 */
@Aspect
@Component
public class PermissionProxy {

    @Autowired
    private HttpSession httpSession;

    /**
     * 拦截注解
     * @param pj
     * @return
     */
    @Around(value = "@annotation(com.lsz.crm.annotation.RequiredPermission)")
    public Object around(ProceedingJoinPoint pj) throws Throwable {
        Object result = null;
        // 得到当前用户拥有的权限 （session作用域）
        List<String> permissions = (List<String>) httpSession.getAttribute("permissions");
        // 判断权限
        if(permissions == null || permissions.size() < 1){
            // 抛出认证异常
            throw new AuthException();
        }
        // 得到对应的目标方法
        MethodSignature methodSignature = (MethodSignature) pj.getSignature();
        // 得到方法上的注解
        RequiredPermission requiredPermission = methodSignature.getMethod().getDeclaredAnnotation(RequiredPermission.class);
        // 判断注解对应的状态码
        if(!(permissions.contains(requiredPermission.code()))) { // 注解权限码不在用户的权限范围内，则抛出异常
            throw new AuthException();
        }
        result = pj.proceed();
        return result;
    }
}
